package com.panda.admin.gateway.security;

import com.panda.admin.constant.SecurityConstants;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;


/**
 * author: tcy
 * createDate: 2023/2/8
 * description: 白名单配置
 */
@Component
public class WhiteListAuthorizationFilter implements WebFilter {

    @Resource
    private WhiteListProperties properties;

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {

        ServerHttpRequest request = serverWebExchange.getRequest();

        String path = request.getURI().getPath();

        PathMatcher pathMatcher = new AntPathMatcher();

        //配置中的白名单路径
        List<String> urls = properties.getIgnoreUrls();

        for (String url:urls){
            if (pathMatcher.match(url,path)){
                request = serverWebExchange.getRequest().mutate().header(SecurityConstants.AUTHORIZATION_HEADER,"").build();
                serverWebExchange = serverWebExchange.mutate().request(request).build();
                return webFilterChain.filter(serverWebExchange);
            }
        }
        return webFilterChain.filter(serverWebExchange);
    }
}
